"""
@Desciption :   
@File       :   for_views.py    
@Contact    :   xiaxiaoshux@163.com

@Modify Time      @Author       @Version    @Change
---------------   -----------   --------    -----------------
2020/7/31 15:27   xiaxiaoshux      1.0      None
"""
import json

import requests
from pyecharts import options as opts
from pyecharts.charts import Line
from pyecharts.charts import Map, Timeline

# 省份列表
name_list = []


def getData():
	"""新创建的"""
	url = "https://voice.baidu.com/newpneumonia/get?target=trend&isCaseIn=0&stage=publish&&qq-pf-to=pcqq.groupnewpneumonia"
	# 请求头，作用：伪装成浏览器反爬虫（虽然这个链接就是用来爬的）
	headers = {
		'user-agent': 'User-Agent: Mozilla/5.0 (Windows NT 10.0 Win64 x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36',
	}
	# 这个网址请求方式为get
	r = requests.get(url, headers)
	info = json.loads(r.text)
	data = info["data"]

	# 遍历省份
	for i in range(len(data)):
		name = data[i]["name"]
		name_list.append(name)

	return data


def BinarySearch(array_strlist, t):
	"""
	二分法找不存在的日期的前一个日期的索引
	:param array_strlist:
	:param t:
	:return:
	"""
	mid = 0
	array = [int(float(x) * 100) for x in array_strlist]
	low = 0
	height = len(array) - 1
	while low < height:
		mid = (low + height) // 2
		if array[mid] < t:
			low = mid + 1

		elif array[mid] > t:
			height = mid - 1
	# else:
	#     return array[mid]

	return mid - 1


def getSpecial(data, date, kind="新增"):
	"""
	获取具体的每个省份、日期下的疫情数据
	:param kind:
	:param data:    getData函数返回的数据（字典类型）
	:param date:    要显示的日期
	:return:        返回指定指定日期的数据
	"""
	province_info = {}
	# 获取想要的日期的下标
	try:
		idx = data[0]["trend"]["updateDate"].index(date)
	except:
		try:
			date_list = date.split('.')
			date_list[1] = str(int(date_list[1]) - 1)
			idx = data[0]["trend"]["updateDate"].index(".".join(date_list))
		except:
			date_list = date.split('.')
			date_list[1] = str(int(date_list[1]) - 2)
			idx = data[0]["trend"]["updateDate"].index(".".join(date_list))

	# print(data[0]["trend"]["updateDate"])
	# print(f'idx={idx}')

	# for i in tqdm(range(len(data))):
	for i in range(len(data)):
		if kind == "确诊":
			# 想要的日期下 确诊人数
			try:
				confirm = data[i]["trend"]["list"][0]["data"][idx]
			except:
				old_date_idx = BinarySearch(data[i]["trend"]["list"][0]["data"], int(float(date) * 100))
				confirm = data[i]["trend"]["list"][0]["data"][old_date_idx]
			province_info.update({data[i]["name"]: confirm})

		if kind == "治愈":
			# 想要的日期下 治愈人数
			try:
				cured = data[i]["trend"]["list"][1]["data"][idx]
			except:
				old_date_idx = BinarySearch(data[i]["trend"]["list"][1]["data"], int(float(date) * 100))
				cured = data[i]["trend"]["list"][1]["data"][old_date_idx]
			province_info.update({data[i]["name"]: cured})

		if kind == "死亡":
			# 想要的日期下 死亡人数
			try:
				death = data[i]["trend"]["list"][2]["data"][idx]
			except:
				old_date_idx = BinarySearch(data[i]["trend"]["list"][2]["data"], int(float(date) * 100))
				death = data[i]["trend"]["list"][2]["data"][old_date_idx]
			province_info.update({data[i]["name"]: death})

		if kind == "新增":
			# 想要的日期下 新增确诊人数
			try:
				newConfirm = data[i]["trend"]["list"][3]["data"][idx]
			except:
				newConfirm = 0
			province_info.update({data[i]["name"]: newConfirm})

	return province_info


def map_init(date=None, kind="新增"):
	"""
	初始化map并返回，被display和lunbo引用
	:param date:    日期，默认为None
	:return:
	"""
	# maptype='china' 只显示全国直辖市和省级
	map_ = Map()
	map_.set_global_opts(
		title_opts=opts.TitleOpts(title=f"2020{date}中国疫情{kind}地图"),
		visualmap_opts=opts.VisualMapOpts(max_=3600, is_piecewise=True,
										  pieces=[
											  {"max": 5000, "min": 1001, "label": ">1000", "color": "#8A0808"},
											  {"max": 1000, "min": 500, "label": "500-1000", "color": "#B40404"},
											  {"max": 499, "min": 100, "label": "100-499", "color": "#DF0101"},
											  {"max": 99, "min": 10, "label": "10-99", "color": "#F78181"},
											  {"max": 9, "min": 1, "label": "1-9", "color": "#F5A9A9"},
											  {"max": 0, "min": 0, "label": "0", "color": "#FFFFFF"},
										  ], ),  # 最大数据范围，分段
	)
	return map_


def display(province_distribution, date, kind="新增"):
	"""
	全国地图-非轮播图
	:param kind:
	:param province_distribution:    省和直辖市
	:param date:
	:return:
	"""

	map_ = map_init()

	map_.add(f"2020{date}中国疫情{kind}地图", data_pair=list(province_distribution.items()), maptype="china", is_roam=True)
	map_.render(f'2020{date}中国疫情地图.html')


def lunbo(data, kind="新增"):
	"""
	全国地图-轮播图
	:param data:    同上
	:param kind:
	:return:
	"""
	# maptype='china' 只显示全国直辖市和省级
	# 制作轮播
	timeline = Timeline()

	# map_list = []
	from datetime import datetime
	for month in range(2, datetime.now().month + 1):
		for day in range(1, 31 if (month != datetime.now().month) else datetime.now().day, 10):
			map_ = map_init()
			nowDate = f"{month}.{day}"
			province_distribution = getSpecial(data, nowDate, kind)
			map_.add(f"2020{month}月{day}日中国疫情{kind}地图", data_pair=list(province_distribution.items()), maptype="china",
					 is_roam=True)
			timeline.add(map_, f"{month}月{day}日")

	timeline.add_schema(is_auto_play=True, play_interval=1000)
	timeline.render("轮播.html")


def getDataByCity(data, city):
	"""
	   获取具体省份、每个日期下的疫情数据
	   :param data:    getData函数返回的数据（字典类型）
	   :param city:    城市
	   :return:        返回指定指定城市的数据
	   """
	res = []
	resItem = []
	# 城市下标
	idx = name_list.index(city)
	# 确诊人数
	# for i in tqdm(range(len(data[idx]['trend']['updateDate']))):
	for i in range(len(data[idx]['trend']['updateDate'])):
		try:
			newConfirm = data[idx]["trend"]["list"][0]["data"][i]
		except:
			newConfirm = 0
		resItem.append(newConfirm)
	res.append(resItem)
	# 治愈人数
	resItem1 = []
	# for i in tqdm(range(len(data[idx]['trend']['updateDate']))):
	for i in range(len(data[idx]['trend']['updateDate'])):
		try:
			newConfirm = data[idx]["trend"]["list"][1]["data"][i]
		except:
			newConfirm = 0
		resItem1.append(newConfirm)
	res.append(resItem1)
	# 死亡人数
	resItem2 = []
	# for i in tqdm(range(len(data[idx]['trend']['updateDate']))):
	for i in range(len(data[idx]['trend']['updateDate'])):
		try:
			newConfirm = data[idx]["trend"]["list"][2]["data"][i]
		except:
			newConfirm = 0
		resItem2.append(newConfirm)
	res.append(resItem2)
	# 新增人数
	resItem3 = []
	# for i in tqdm(range(len(data[idx]['trend']['updateDate']))):
	for i in range(len(data[idx]['trend']['updateDate'])):
		try:
			newConfirm = data[idx]["trend"]["list"][3]["data"][i]
		except:
			newConfirm = 0
		resItem3.append(newConfirm)
	res.append(resItem3)
	# print(res[2])
	return res


def CityHandler(CityData, city, data):
	x_data = data[0]['trend']['updateDate']
	(
		Line()
			.add_xaxis(xaxis_data=x_data)
			.add_yaxis(
			series_name="确诊人数",
			y_axis=CityData[0],
			label_opts=opts.LabelOpts(is_show=False),
		)
			.add_yaxis(
			series_name="治愈人数",
			y_axis=CityData[1],
			label_opts=opts.LabelOpts(is_show=False),
		)
			.add_yaxis(
			series_name="死亡人数",
			y_axis=CityData[2],
			label_opts=opts.LabelOpts(is_show=False),
		)
			.add_yaxis(
			series_name="新增确诊人数",
			y_axis=CityData[3],
			label_opts=opts.LabelOpts(is_show=False),
		)
			.set_global_opts(
			title_opts=opts.TitleOpts(title=city),
			tooltip_opts=opts.TooltipOpts(trigger="axis"),
			yaxis_opts=opts.AxisOpts(
				type_="value",
				axistick_opts=opts.AxisTickOpts(is_show=True),
				splitline_opts=opts.SplitLineOpts(is_show=True),
			),
			xaxis_opts=opts.AxisOpts(type_="category", boundary_gap=False),
		)
			.render(city + ".html")
	)


def allProvince_remainConfirm():
	data = getData()
	# 要返回的json数据
	ret_data = []

	from datetime import datetime
	for month in range(2, datetime.now().month):
		# 按31天计算（getSpecial中有纠正日期功能）
		day = 31
		nowDate = f"{month}.{day}"
		# print(nowDate)
		# 找当前的日期下的各个省份的数据
		confirm_num = getSpecial(data, nowDate, "确诊")
		all_confirm_num = sum(confirm_num.values())
		# print(f"confirm_num=\n{confirm_num}")
		cured_num = getSpecial(data, nowDate, "治愈")
		all_cured_num = sum(cured_num.values())
		newConfirm_num = getSpecial(data, nowDate, "新增")
		all_newConfirm_num = sum(newConfirm_num.values())
		death_num = getSpecial(data, nowDate, "死亡")
		all_death_num = sum(death_num.values())

		ret_data.append({"date": f"{month}月", "类型": "确诊", "数量": all_confirm_num})
		ret_data.append({"date": f"{month}月", "类型": "治愈", "数量": all_cured_num})
		ret_data.append({"date": f"{month}月", "类型": "新增", "数量": all_newConfirm_num})
		ret_data.append({"date": f"{month}月", "类型": "死亡", "数量": all_death_num})
		ret_data.append({"date": f"{month}月", "类型": "现存", "数量": all_confirm_num - all_cured_num})


if __name__ == '__main__':
	print(getData())
